package com.report.service;

import com.report.dto.TreeNode;
import com.report.entity.Project;
import com.report.repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    public Project saveProject(Project project) {
        return projectRepository.save(project);
    }

    public Project getProject(String sjxmbh) {
        List<Project> project = projectRepository.findByBsdw(sjxmbh);
        if (project.size() > 0) {
            return project.get(0);
        }
        return null;
    }


    public void deleteProject(String sjxmbh) {
        projectRepository.deleteBySjxmbh(sjxmbh);
    }

    public List<TreeNode> buildCompanyTree(String bsdwxydm) {
        List<TreeNode> treeNodes = new ArrayList<>();

        // 查询当前企业
        List<Project> projects = projectRepository.findByBsdwxydm(bsdwxydm);
        if (!projects.isEmpty()) {
            Project company = projects.get(0);
            TreeNode node = new TreeNode();
            node.setXydm(company.getBsdwxydm());
            node.setName(company.getBsdw());

            // 递归查询子企业
            List<Project> subCompanies = projectRepository.findBySjdwxydm(bsdwxydm);
            List<TreeNode> children = new ArrayList<>();
            for (Project sub : subCompanies) {
                children.addAll(buildCompanyTree(sub.getBsdwxydm()));
            }
            node.setChildren(children);
            treeNodes.add(node);
        }
        return treeNodes;
    }

    public HashMap<String, String> findAll() {
        List<Project> ls = projectRepository.findAll();
        HashMap<String, String> map = new HashMap<>();
        for (Project project : ls) {
            if (!map.containsKey(project.getBsdwxydm())) {
                map.put(project.getBsdwxydm(), project.getBsdw());
            }
        }
        return map;
    }
}
